﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Toggle))]
public class ToggleBehavior : MonoBehaviour
{
    public RectTransform _targetGraphic;
    public RectTransform _graphic;
    public Toggle mToggle
    {
        get
        {
            if (_toggle == null)
                _toggle = gameObject.GetComponent<Toggle>();
            return _toggle;
        }
    }
    private Toggle _toggle;
    public bool cacthValue { get { return _cacthValue; } }
    private bool _cacthValue;
    private void Awake()
    {
        mToggle.onValueChanged.RemoveListener(OnToggle);
        mToggle.onValueChanged.AddListener(OnToggle);
        OnToggle(mToggle.isOn);
    }

    public void siwtchToggle(bool isOn)
    {
        if (!Application.isPlaying)
        {
            _cacthValue = isOn;
            Transform _tg = _targetGraphic != null ? _targetGraphic.transform : mToggle.targetGraphic.transform;
            Transform _g = _graphic != null ? _graphic.transform : mToggle.graphic.transform;
            if (enabled)
            {
                if (_tg != null)
                    OnToggle(_tg, !isOn, _g);
                if (_g != null)
                    OnToggle(_g, isOn, _tg);
            }
            else
            {
                if (_tg != null)
                    OnToggle(_tg, true, _g);
                if (_g != null)
                    OnToggle(_g, false, _tg);
            }
        }
        else
        {
            _cacthValue = isOn;
            Transform _tg = _targetGraphic != null ? _targetGraphic.transform : mToggle.targetGraphic.transform;
            Transform _g = _graphic != null ? _graphic.transform : mToggle.graphic.transform;
            if (_tg != null)
                OnToggle(_tg, !isOn, _g);
            if (_g != null)
                OnToggle(_g, isOn, _tg);
        }
    }
    private void OnToggle(bool isOn)
    {
        _cacthValue = isOn;
        Transform _tg = _targetGraphic != null ? _targetGraphic.transform : mToggle.targetGraphic.transform;
        Transform _g = _graphic != null ? _graphic.transform : mToggle.graphic.transform;

        if (_tg != null)
            OnToggle(_tg, !isOn, _g);
        if (_g != null)
            OnToggle(_g, isOn, _tg);
    }

    private void OnToggle(Transform target, bool isOn, Transform ignorseTran)
    {
        //if (target == ignorseTran )
        //    return;
        Graphic _g = target.GetComponent<Graphic>();
        if (_g != null && _g != mToggle.graphic && mToggle.targetGraphic != target)
        {
            float _a = isOn ? 1 : 0;
            _g.color = new Color(_g.color.r, _g.color.g, _g.color.b, _a);
        }
        for (int i = 0; i < target.childCount; i++)
        {        
            OnToggle(target.GetChild(i), isOn, ignorseTran);
        }
    }
}
